<template>
  <el-dialog v-model="dialogFormVisible" title="新增" @close="resetForm" draggable append-to-body width="30%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="left"
      v-loading="formLoading"
    >
      <!-- <el-form-item label="联系人">
        <el-input v-model="formData.username" placeholder="请输入" />
      </el-form-item> -->
      <el-form-item prop="company_name" label="公司名称">
        <el-input v-model="formData.company_name" placeholder="请输入" />
      </el-form-item>
      <!-- <el-form-item label="联系方式">
        <el-input v-model="formData.contact_number" placeholder="请输入" />
      </el-form-item> -->
      <el-form-item label="成立日期">
        <el-date-picker
          v-model="formData.founded_date"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          type="date"
          placeholder="请选择"
        />
        <!--          <el-input v-model="formData.founded_date" placeholder="请输入" />-->
      </el-form-item>
      <!-- <el-form-item label="所在城市">
        <el-input v-model="formData.city" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="所在行业">
        <el-input v-model="formData.industry" placeholder="请输入" />
      </el-form-item> -->
      <el-form-item label="业务员">
        <el-select v-model="formData.uid" placeholder="请选择" @change="handleUidChange">
          <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类别">
        <el-select v-model="formData.company_type" placeholder="请选择">
          <el-option v-for="item in typeList" :key="item.data_value" :label="item.data_name" :value="item.data_value" />
          <!-- <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id" /> -->
        </el-select>
        <el-button type="primary" @click="handleUid" plain>中介</el-button>
      </el-form-item>
      <!-- <el-form-item label="是否开票" prop="invoicing_type">
        <el-radio-group v-model="formData.invoicing_type">
          <el-radio v-for="option in invoicingList" :key="option.data_value" :label="Number(option.data_value)">
            {{ option.data_name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="先款先票" prop="check_type">
        <el-radio-group v-model="formData.check_type">
          <el-radio v-for="option in checkList" :key="option.data_value" :label="Number(option.data_value)">
            {{ option.data_name }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="星级" prop="star_rating">
        <el-rate v-model="formData.star_rating" clearable />
      </el-form-item> -->
      <el-form-item prop="card_name" label="名字">
        <el-input v-model="formData.card_name" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="card_bank" label="银行">
        <el-input v-model="formData.card_bank" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="card_number" label="卡号">
        <el-input v-model="formData.card_number" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="wx_name" label="微信名称">
        <el-input v-model="formData.wx_name" placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="wx_code" label="微信收款码">
        <el-image
          :src="formData.wx_codes"
          style="margin: 10px; width: 100px; height: 100px"
          fit="cover"
          :preview-src-list="wxLists"
          :initial-index="1"
        />
        <el-button type="primary" @click="handleCoverUpload('wx_code')">上传图片</el-button>

        <!-- <el-input v-model="formData.wx_code" placeholder="请输入" /> -->
      </el-form-item>
      <el-form-item prop="zfb_name" label="支付宝名称">
        <el-input v-model="formData.zfb_name" placeholder="请输入" />
      </el-form-item>
      <!-- 图库图片上传 -->
      <el-form-item label="支付宝收款码">
        <!-- 图库图片展示 -->
        <div class="uploaded-images">
          <el-image
            :src="formData.zfb_codes"
            style="margin: 10px; width: 100px; height: 100px"
            fit="cover"
            :preview-src-list="zfbLists"
            :initial-index="1"
          />
        </div>

        <el-button type="primary" @click="handleCoverUpload('zfb_code')">上传图片</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <!-- <el-button @click="dialogVisible = false">取消</el-button> -->
      <el-button type="primary" @click="handleCreate">确认</el-button>
    </template>
    <UploadImageDialog
      ref="uploadImageDialogRef"
      @upload-complete="handleUploadComplete"
      @upload-cancel="handleUploadCancel"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, ComponentPublicInstance } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { createCompanyAddApi, dictDataGetListApi } from "@/api/conventional"
// import { GetListResponseData } from "@/api/system/types/admin"
import { getAdminRoleListApi } from "@/api/system"
import UploadImageDialog from "./price/imageUploader.vue"

const uploadImageDialogRef = ref<ComponentPublicInstance<InstanceType<typeof UploadImageDialog>> | null>(null)

// const company_type_options = ref([
//   { id: 1, label: "客户" },
//   { id: 2, label: "平台" },
//   { id: 3, label: "中介" }
// ])
const listData = ref<any>([])
const formLoading = ref<boolean>(false)
const dialogFormVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
// 定义一个接口来描述 reactive 对象的结构
interface formDataObject {
  username: string
  company_name: string
  contact_number: string
  founded_date: string
  city: string
  industry: string
  uid: number
  company_type: number | string
  invoicing_type: number | string
  check_type: number | string
  star_rating: number
  card_number: string | undefined | null
  zfb_code: string | undefined | null
  wx_code: string | undefined | null
  zfb_codes: string | undefined
  wx_codes: string | undefined
  card_name: string | undefined
  card_bank: string | undefined
  zfb_name: string | undefined
  wx_name: string | undefined
}
const formData: formDataObject = reactive({
  username: "",
  company_name: "",
  contact_number: "",
  founded_date: "",
  city: "",
  industry: "",
  uid: 0,
  company_type: "1",
  check_type: 2,
  invoicing_type: 2,
  star_rating: 1,
  card_number: "",
  zfb_code: "",
  wx_code: "",
  zfb_codes: "",
  wx_codes: "",
  card_name: "",
  card_bank: "",
  zfb_name: "",
  wx_name: ""
})
const formRules: FormRules = reactive({
  username: [{ required: true, trigger: "blur", message: "请输入联系人" }],
  company_name: [{ required: true, trigger: "blur", message: "请输入公司名称" }],
  contact_number: [{ required: true, trigger: "blur", message: "请输入联系方式" }],
  founded_date: [{ required: true, trigger: "blur", message: "请输入成立日期" }],
  city: [{ required: true, trigger: "blur", message: "请输入所在城市" }],
  industry: [{ required: true, trigger: "blur", message: "请输入所在行业" }],
  uid: [{ required: true, trigger: "change", message: "请选择业务员" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      createCompanyAddApi(formData)
        .then(() => {
          ElMessage.success("新增成功")
        })
        .finally(() => {
          dialogFormVisible.value = false
        })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
const resetForm = () => {
  formData.username = ""
  formData.company_name = ""
  formData.contact_number = ""
  formData.founded_date = ""
  formData.city = ""
  formData.industry = ""
  formData.uid = 0
  formData.company_type = "1"
  formData.check_type = 2
  formData.invoicing_type = 2
  formData.star_rating = 1
  formData.card_number = null
  formData.card_bank = undefined
  formData.zfb_code = null
  formData.wx_code = null
  formData.zfb_codes = undefined
  formData.wx_codes = undefined
  formData.wx_name = undefined
  formData.zfb_name = undefined
  formData.card_name = undefined
}
const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}

// #region 公司类型
const companyTypeFun = async () => {
  await INVOICINGFun()
  await checkFun()
  await typeFun()
}
const invoicingList = ref<any[]>([])
const INVOICINGFun = async () => {
  const res = await dictDataGetList("COMPANY_INVOICING")
  invoicingList.value = res.data
}
const checkList = ref<any[]>([])
const checkFun = async () => {
  const res = await dictDataGetList("COMPANY_CHECK")
  checkList.value = res.data
}
const typeList = ref<any[]>([])
const typeFun = async () => {
  const res = await dictDataGetList("COMPANY_TYPE")
  typeList.value = res.data
}
const dictDataGetList = async (type: string) => {
  try {
    const res = await dictDataGetListApi({ type_code: type })
    return res
  } catch (error) {
    console.error("Error:", error)
  }
}

// #endregion

const handleUidChange = (value: any) => {
  if (value == 22) {
    formData.uid = 22
    formData.company_type = "3"
  }
}
const handleUid = () => {
  formData.uid = 22
  formData.company_type = "3"
}

const show = () => {
  getAdminList()
  companyTypeFun()
  dialogFormVisible.value = true
}
defineExpose({ show })

// #region 商家码上传
const handleCoverUpload = (contextKey: string) => {
  if (uploadImageDialogRef.value) {
    uploadImageDialogRef.value.openUploadDialog(contextKey)
  }
}
const handleUploadComplete = (row: any) => {
  console.log(row)
  console.log("sadasdasd")
  const contextKey = row.contextKey
  const file = row.fileList

  if (contextKey === "wx_code") {
    formData.wx_code = file.path
    formData.wx_codes = file.url
    wxLists.value.push(file.url)
  }
  if (contextKey === "zfb_code") {
    formData.zfb_code = file.path
    formData.zfb_codes = file.url
    zfbLists.value.push(file.url)
  }
  console.log("formData")
  console.log(formData)
}
const handleUploadCancel = (contextKey: string) => {
  console.log(contextKey)
}
const zfbLists = ref<string[]>([])
const wxLists = ref<string[]>([])
// #endregion
</script>

<style scoped lang="scss">
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
